Reusing Code and Searching
Beauty of object-oriented programming language is developing program fast using the existing code, reusing the code. The concept of code reusability helps to develop program fast and at the same time make code maintenance easy. Here, a simple Java program is presented, in which user provided text is searched in the database and if search text is found the id related to the text is displayed. Table accessed is: product (pid, pname, qty); user provides name of product in the text field; and as clicks the button search is performed in the database.
In this program, separate class, conn, is created which makes connection with the provided database. Constructor function of this class takes name of database and makes connection with that database; getConnection function returns object of the connection class. This object of this class can be used in other programs in which same database server but different database is used.
package ui_first; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.ResultSet; class conn{ Connection c; public conn(String db) { try{ String url = "jdbc:mysql://localhost:3306/"+db; String un = "root"; String pw = ""; c = DriverManager.getConnection(url,un,pw); System.out.println("Connected!"); }catch(SQLException ie) {System.out.println(ie.getMessage());} } public Connection getConnetion() { return c; } } class connection extends JFrame implements ActionListener{ conn c; JTextField jt; JButton btn; Connection cc; JLabel lbl; public connection() { c = new conn("test"); cc = c.getConnetion();//getting connection from con object; jt = new JTextField(14); btn = new JButton("Search!!!"); lbl = new JLabel(); setLayout(new GridLayout(5,1)); setSize(300,200); setLocationRelativeTo(null); setTitle("Search"); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(jt); add(btn); add(lbl); btn.addActionListener(this); } public void actionPerformed(ActionEvent aeee) { String sql = "select * from product where pname= '"+jt.getText()+"'"; try{ Statement stmt = cc.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { lbl.setText("ID: "+rs.getInt(1)); } }catch(SQLException se) {} } public static void main(String[] ar) { SwingUtilities.invokeLater(new Runnable() { public void run() { new connection(); } }); } }